﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebAppAuthAdmin.AuthApiManagementServiceReference;
using WebAppAuthAdmin.Code;
using Web.Framework;
using AuthApi.Contracts;
using WebAppAuthAdmin.Code.Security;

namespace WebAppAuthAdmin.App
{
    public partial class CompanyEdit : BasePage
    {
        private Company companyToEdit
        {
            get
            {
                return (Company)ViewState["companyToEdit"];
            }
            set
            {
                ViewState["companyToEdit"] = value;
            }           
        }

        private List<LinkButton> actionButtons = new List<LinkButton>();
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            LinkButton crearContactoButton = new LinkButton();
            crearContactoButton.ID = "guardarButton";
            crearContactoButton.Text = "Guardar";
            crearContactoButton.Click += new EventHandler(lnkGuardar_Click);
            actionButtons.Add(crearContactoButton);

            base.LoadContextActions(actionButtons);
        }

        protected override void ApplySecurity()
        {
            LinkButton lnkButton =  actionButtons.Where(b => b.ID == "guardarButton").Single();

            if (companyToEdit.Id == 0)
            {
                lnkButton.Visible = HasPermissionFor(AppSecurity.APP_CREATE_COMPANY);
            }
            else
            {
                lnkButton.Visible = HasPermissionFor(AppSecurity.APP_EDIT_COMPANY_ID_ + companyToEdit.Id.ToString());
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {                
                if (!this.IsPostBack)
                {
                    if (!String.IsNullOrEmpty(this.Request.QueryString["Id"]))
                    {
                        int companyId = Convert.ToInt32(this.Request.QueryString["Id"]);
                        // company existente
                        companyToEdit = WebServiceHelper.GetCompanyById(companyId);
                        Bind();
                    }
                    else
                    {
                        // nueva
                        companyToEdit = new Company();
                    }
                }

                if (companyToEdit.Id != 0)
                {
                    HasPermissionToSeeMe(AppSecurity.APP_VIEW_COMPANY_ID_ + companyToEdit.Id.ToString());
                }
                else
                {
                    HasPermissionToSeeMe(AppSecurity.APP_CREATE_COMPANY);
                }

            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private void Bind()
        {
            if (this.companyToEdit.Id != 0)
            {
                this.txtCodigoEmpresa.Text = Convert.ToString(this.companyToEdit.Id);
                this.txtCodigoEmpresa.CssClass = "readonly";
                this.txtCodigoEmpresa.ReadOnly = true;
            }
            
            this.txtNombreEmpresa.Text = this.companyToEdit.Name;
            this.txtDominio.Text = this.companyToEdit.Domain;
            this.txtPathAd.Text = this.companyToEdit.AdPath;
            this.txtUsuarioAd.Text = this.companyToEdit.AdUser;
            //this.txtUsuarioAd.Text = 

            this.Grid.DataSource = this.companyToEdit.Applications;
            this.Grid.DataBind();
        }

        protected void Grid_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    WebApplicationInfoIncluded operation = (WebApplicationInfoIncluded)e.Row.DataItem;

                    CheckBox chkSelect = (CheckBox)e.Row.Cells[0].FindControl("chkSelectRow");
                    chkSelect.Checked = operation.IsIncluded;
                    if (operation.IsIncluded)
                    {
                        this.hidCheckedRows.Value += string.Format("#{0}#", operation.Id);
                    }                    
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void Grid_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                if (e.CommandName == "verroles")
                {
                    int operationId = Convert.ToInt32(this.Grid.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
                    this.Response.Redirect(string.Format("/App/OperationViewRoles.aspx?Id={0}", operationId, true));
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private void Save()
        {
            this.companyToEdit = WebServiceHelper.SaveCompany(this.companyToEdit);
        }

        private void SetData()
        {
            if (!string.IsNullOrEmpty(this.txtCodigoEmpresa.Text))
            {
                companyToEdit.Id = Convert.ToInt32(this.txtCodigoEmpresa.Text);
            }

            companyToEdit.Name = this.txtNombreEmpresa.Text;
            this.companyToEdit.AdPath = this.txtPathAd.Text;
            this.companyToEdit.AdUser = this.txtUsuarioAd.Text;
            if (!String.IsNullOrEmpty(this.txtPasswordAd.Text))
            {
                this.companyToEdit.AdPassword = this.txtPasswordAd.Text;
            }

            this.companyToEdit.Domain = this.txtDominio.Text;
            List<int> selectedRowsIds = UIHelper.GetSelectedRowIds(this.hidCheckedRows.Value);

            foreach (var application in this.companyToEdit.Applications)
            {
                if (selectedRowsIds.Contains(application.Id))
                {
                    application.IsIncluded = true;
                }
                else
                {
                    application.IsIncluded = false;
                }
            }

            this.hidCheckedRows.Value = string.Empty;  
        }

        private void Validar()
        {
            // TODO
        }

        protected void lnkGuardar_Click(object sender, EventArgs e)
        {
            try
            {
                Validar();
                SetData();
                Save();
                this.Response.Redirect("/App/CompanyList.aspx", true);
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }        
    }
}